package org.makcro.sms.services.chat.base.filters;

import java.text.MessageFormat;

import org.apache.log4j.Logger;
import org.makcro.sms.services.chat.base.dao.SubscriberDao;
import org.makcro.sms.services.chat.model.BulkGroupItem;
import org.makcro.sms.services.chat.model.Question;

import com.klikmee.sms.cef.services.Service;

/**
 * Message filter that is activated on user unsubscribe request and is used to
 * unsubscribe user from receiving bulk messages sent from chat service.
 * 
 * @author makcro
 * 
 */
public class UnsubscribeFilter extends AbstractFilter {

	/**
	 * Logger instance
	 */
	private Logger			logger			= Logger.getLogger( UnsubscribeFilter.class );

	/**
	 * Text of the info message to be sent to the user
	 */
	private String			unSubscribeInfoText;

	/**
	 * Core id of the service used to unsubscribe user
	 */
	private Long			unSubscribeServiceId;

	/**
	 * Core id of the charging used to unsubscribe the user
	 */
	private Long			unSubscribeChargingId;

	/**
	 * Instance of subscriber dao used to invalidate sessions
	 */
	private SubscriberDao	subscriberDAO	= null;

	/**
	 * Tests question for activation expression and if matched tries to
	 * unsubscribe user with the given id, by updating
	 * {@link BulkGroupItem#setDisabled(boolean)} property.
	 * 
	 */
	@Override
	public boolean process(Question question) {

		if (question.getQuestion().matches( activationExpression )) {

			logger.info( MessageFormat.format( "Successfull match on Unsubscribe filter, core message id = [{0}]", question.getCoreID() ) );

			int noOfUpdatedRows = subscriberDAO.disableSubscription( question.getFromNumber() );

			Long infoCoreId = this.coreAdapter.sendMessage( this.unSubscribeChargingId, this.unSubscribeServiceId, Service.SERVICE_FLAG_SEMANTIC_OK, question.getCoreID(), this.unSubscribeInfoText );

			// update question so it's not visible to operaters
			question.setVisable( false );

			persistAnswer( question, unSubscribeInfoText, infoCoreId, false );

			logger.info( MessageFormat.format( "Disabled subscription for [{0}]", question.getFromNumber() ) );
			return true;
		}
		return false;
	}

	public void setUnSubscribeInfoText(String unSubscribeInfoText) {
		this.unSubscribeInfoText = unSubscribeInfoText;
	}

	public void setUnSubscribeServiceId(Long unSubscribeServiceId) {
		this.unSubscribeServiceId = unSubscribeServiceId;
	}

	public void setUnSubscribeChargingId(Long unSubscribeChargingId) {
		this.unSubscribeChargingId = unSubscribeChargingId;
	}

	public void setSubscriberDAO(SubscriberDao subscriberDAO) {
		this.subscriberDAO = subscriberDAO;
	}

	@Override
	public String toString() {
		return "UnsubscribeFilter";
	}
}
